var listColumns = [[
    {field: "id", checkbox: true},
    {field: "code", title: "CODE", align: "center", width: 140,formatter: function (value, rowData, index){
        if(value == '0'){
            return "选项";
        }else if(value == '1'){
            return "判定常用";
        }
        return "";
    }},
    {field: "words", title: "文字", align: "center", width: 140},
    {field: "picUrl", title: "图片路径", align: "center", width: 200},
    {field: "parentPosition", title: "上级位置", align: "center", width: 140},
    {field: "pagePosition", title: "位置", align: "center", width: 120},
    {field: "description", title: "描述", align: "center", width: 120},
    {field: "updator", title: "更新人", align: "center", width: 120},
    {field: "updateTime", title: "更新时间", align: "center", width: 140},
    {
        field: "handle", title: "操作", align: "center", width: 120, formatter: function (value, rowData, index) {
        return '<a class="layui-btn layui-btn-xs"  onclick="editData(' + index + ')">编辑</a>'
    }
    }

]];

layui.config({
    base: "../static/agent-ui/js/"
});

$.fn.toJSON = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        var name = this.name;
        var value = this.value;
        var paths = this.name.split(".");
        var len = paths.length;
        var obj = o;
        $.each(paths, function (i, e) {
            if (i == len - 1) {
                if (obj[e]) {
                    if (!obj[e].push) {
                        obj[e] = [obj[e]];
                    }
                    obj[e].push(value || '');
                } else {
                    obj[e] = value || '';
                }
            } else {
                if (!obj[e]) {
                    obj[e] = {};
                }
            }
            obj = o[e];
        });
    });
    return o;
};

layui.use(["laypage", "layer", "validator", "tools", "form", "select", "laydate", "upload"], function () {
    var form = layui.form;
    var date = layui.laydate;

    var layer = layui.layer;

    $(function () {
        $('#list').datagrid({
            columns: listColumns,
            fitColumns: false,
            fit: true,
            singleSelect: true,
            pagination: true,
            pageSize: 30,
            pageList: [30, 50, 100, 1000],
            toolbar: '#receivedListHeader',
            method: 'get',
            url: ctx + '/picWord/list',
            onLoadSuccess: function () {


            }
        });


    });




});


$("#addData").on("click", function () {
    var form = layui.form;
    /* 再弹出添加界面 */
    layer.open({
        type: 1,
        title: "添加图文信息",
        skin: "myclass",
        area: ["50%", "85%"],
        content: $("#add").html(),
        success: function (layero, index) {
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            form.render('select'); //刷新select选择框渲染
            uploadRender(layero);
        },
        btn: ['提交', '关闭'],
        yes: function (index, layero) {
            form.on('submit(fromContent)', function (data) {
                add(index, layero)
            });
        },
        btn2: function (index, layero) {
            layer.close(index);
        }
    });

});
function add(index,layero) {
    $.ajax({
        url:ctx+'/picWord/insert',
        type : 'POST',
        data:$(layero).find("form[id=add_form]").toJSON(),
        success:function (result) {
            var layer = layui.layer;
            var json = JSON.parse(result);
            if(json.code=='0'){
                layer.close(index);
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }

        },
        error:function (result) {
            var json = JSON.parse(result);
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: '新增失败'
            });

        }
    });
}

//普通图片上传
function uploadRender(layero) {
    var $ = layui.jquery
        , upload = layui.upload;
    layui.each(layero.find("#btn1"),function (index,elem) {
        var uploadInst = upload.render({
            elem: elem
            , url: ctx + '/picWord/upload/'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    layero.find('#img1').attr('src', result); //图片链接（base64）
                });
            }
            , done: function (res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                $(layero).find('input[name=picUrl]').val(res.picUrl);
                //上传成功
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });
    })
}

// 编辑
function editData(index) {
    var rows = $('#list').datagrid('getRows');
    var json = rows[index];
    var form = layui.form;
    layer.open({
        type: 1,
        title: "编辑图文信息",
        skin: "myclass",
        area: ["50%", "85%"],
        content: $("#add" ).html(),
        success: function (layero, index) {
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            $(layero).find('select[name=code]').val(json.code);
            $(layero).find('input[name=words]').val(json.words);
            $(layero).find('input[name=pagePosition]').val(json.pagePosition);
            $(layero).find('input[name=parentPosition]').val(json.parentPosition);
            $(layero).find('input[name=picUrl]').val(json.picUrl);
            form.render('select'); //刷新select选择框渲染
            uploadRender(layero);
        },
        btn: ['提交', '关闭'],
        yes: function (index, layero) {
            form.on('submit(fromContent)', function (data) {
                update(index, json.id, layero)
            });
        },
        btn2: function (index, layero) {
            layer.close(index);
        }
    });
}
function update(index, id, layero) {
    $.ajax({
        url: ctx + '/picWord/update/' + id,
        type: 'POST',
        data: $(layero).find("form[id=add_form]").toJSON(),
        success: function (result) {
            var layer = layui.layer;
            var json = JSON.parse(result);
            if (json.code == '0') {
                layer.close(index);
                $('#list').datagrid('reload');
            } else {
                layer.open({
                    title: '报错了'
                    , content: json.msg
                });
            }
        },
        error: function (result) {
            var json = JSON.parse(result);
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                , content: '更新失败'
            });

        }
    });
}




